package npr;

import processing.core.*;

import javax.media.opengl.*;
import com.sun.opengl.util.*;


/**
 * Detects contours by rendering the backfacing polygons again with a polygon
 * offset after the main rendering pass. This results in wriggly lines and is a
 * simple and efficient way to achieve some extent of stylization.
 */
public class OffsetContours extends HybridLines{
    
    /**
     * Shader for line colour.
     */
    protected GLSL color;

    /**
     * Creates an OffsetContours object and initializes it.
     */
    public OffsetContours(){

	color=new GLSL();
        color.loadVertexShader("color.vert");
        color.loadFragmentShader("color.frag");
        color.useShaders();
    }

    /**
     * Sets the polygon offset.
     *
     * @param width amount of the polygon offset
     */
    public void setWidth(float width){
	this.width= -width;
    }


    /**
     * Renders the backfacing polygons with a polygon offset.
     * You don't have to call this medhod. It is called by the renderer.
     */
    public void postProcess(){
	
	renderer= (NPR)parent.g;
	gl= renderer.gl;
	
	gl.glShadeModel(GL.GL_FLAT);
	gl.glDisable(GL.GL_NORMALIZE);
	//lighting is disabled by default
	//gl.glDisable(GL.GL_LIGHTING);
	gl.glEnable(GL.GL_DEPTH_TEST);
	gl.glDepthFunc(GL.GL_LEQUAL);
	gl.glEnable(GL.GL_CULL_FACE);
	gl.glCullFace(GL.GL_FRONT);
	gl.glEnable(GL.GL_POLYGON_OFFSET_FILL);
	gl.glPolygonOffset(width, 0f);
	
	color.startShader();

	int location= color.getUniformLocation("color");
	color.setFloatVec4(location, red, green, blue, alpha);

	render();
	color.endShader();

	gl.glShadeModel(GL.GL_SMOOTH);
	gl.glEnable(GL.GL_NORMALIZE);
	//lighting is disabled by default
	//gl.glEnable(GL.GL_LIGHTING);
	gl.glCullFace(GL.GL_BACK);
	gl.glDisable(GL.GL_CULL_FACE);
	gl.glDisable(GL.GL_POLYGON_OFFSET_FILL);
	
    }
}